import React, { useState, useEffect } from 'react'
import { Upload, X, Download, Eye, Trash2 } from 'lucide-react'
import { equipmentMaintenanceAPI } from '../services/api'

const ImageUpload = React.forwardRef(({ repairRecordId, onImagesChange, readOnly = false, allowTempUpload = false }, ref) => {
  const [images, setImages] = useState([])
  const [tempFiles, setTempFiles] = useState([]) // 临时文件存储
  const [uploading, setUploading] = useState(false)
  const [dragOver, setDragOver] = useState(false)

  // 加载已有图片
  useEffect(() => {
    if (repairRecordId) {
      loadImages()
    }
  }, [repairRecordId])

  const loadImages = async () => {
    try {
      const response = await equipmentMaintenanceAPI.repairRecordImages.getAll(repairRecordId)
      const imageList = response?.results || []
      setImages(imageList)
      if (onImagesChange) {
        onImagesChange(imageList)
      }
    } catch (error) {
      console.error('加载图片失败:', error)
    }
  }

  const handleFileSelect = (files) => {
    const fileArray = Array.from(files)
    const validFiles = fileArray.filter(file => {
      if (!file.type.startsWith('image/')) {
        alert(`文件 ${file.name} 不是图片格式`)
        return false
      }
      if (file.size > 10 * 1024 * 1024) {
        alert(`文件 ${file.name} 超过10MB限制`)
        return false
      }
      return true
    })
    
    if (validFiles.length > 0) {
      uploadFiles(validFiles)
    }
  }

  const uploadFiles = async (files) => {
    // 如果允许临时上传且没有recordId，则临时存储文件
    if (allowTempUpload && !repairRecordId) {
      const newTempFiles = files.map(file => ({
        file,
        id: Date.now() + Math.random(), // 临时ID
        name: file.name,
        size: file.size,
        preview: URL.createObjectURL(file)
      }))
      
      setTempFiles(prev => [...prev, ...newTempFiles])
      
      // 通知父组件文件变化
      if (onImagesChange) {
        onImagesChange([...tempFiles, ...newTempFiles])
      }
      return
    }

    if (!repairRecordId) {
      alert('请先保存维修记录，然后再上传图片')
      return
    }

    setUploading(true)
    try {
      const formData = new FormData()
      formData.append('repair_record', repairRecordId)
      
      for (let file of files) {
        formData.append('images', file)
      }

      await equipmentMaintenanceAPI.repairRecordImages.batchUpload(formData)
      await loadImages() // 重新加载图片列表
    } catch (error) {
      console.error('上传失败:', error)
      alert('图片上传失败，请重试')
    } finally {
      setUploading(false)
    }
  }

  const handleDelete = async (imageId) => {
    // 检查是否是临时文件
    const tempFileIndex = tempFiles.findIndex(file => file.id === imageId)
    if (tempFileIndex !== -1) {
      // 删除临时文件
      const updatedTempFiles = tempFiles.filter(file => file.id !== imageId)
      setTempFiles(updatedTempFiles)
      
      // 通知父组件文件变化
      if (onImagesChange) {
        onImagesChange([...images, ...updatedTempFiles])
      }
      return
    }

    // 删除已上传的图片
    if (window.confirm('确定要删除这张图片吗？')) {
      try {
        await equipmentMaintenanceAPI.repairRecordImages.delete(imageId)
        await loadImages()
      } catch (error) {
        console.error('删除失败:', error)
        alert('删除失败，请重试')
      }
    }
  }

  const handleDownload = (imageId) => {
    equipmentMaintenanceAPI.repairRecordImages.download(imageId)
  }

  const handlePreview = (imageId) => {
    const previewUrl = equipmentMaintenanceAPI.repairRecordImages.preview(imageId)
    window.open(previewUrl, '_blank')
  }

  const handleDragOver = (e) => {
    e.preventDefault()
    setDragOver(true)
  }

  const handleDragLeave = (e) => {
    e.preventDefault()
    setDragOver(false)
  }

  const handleDrop = (e) => {
    e.preventDefault()
    setDragOver(false)
    const files = e.dataTransfer.files
    handleFileSelect(files)
  }

  // 添加批量上传临时文件的方法
  const uploadTempFiles = async (recordId) => {
    if (tempFiles.length === 0) return
    
    setUploading(true)
    try {
      const formData = new FormData()
      formData.append('repair_record', recordId)
      
      for (let tempFile of tempFiles) {
        formData.append('images', tempFile.file)
      }

      await equipmentMaintenanceAPI.repairRecordImages.batchUpload(formData)
      
      // 清空临时文件
      setTempFiles([])
      
      // 重新加载图片列表
      await loadImages()
    } catch (error) {
      console.error('上传失败:', error)
      alert('图片上传失败，请重试')
    } finally {
      setUploading(false)
    }
  }
  
  // 暴露上传临时文件的方法给父组件
  React.useImperativeHandle(ref, () => ({
    uploadTempFiles
  }))

  return (
    <div style={{ width: '100%' }}>
      {/* 上传区域 - 只在非只读模式下显示 */}
      {!readOnly && (
        <div
          style={{
            border: `2px dashed ${dragOver ? '#007bff' : '#ddd'}`,
            borderRadius: '8px',
            padding: '20px',
            textAlign: 'center',
            backgroundColor: dragOver ? '#f8f9fa' : '#fafafa',
            cursor: 'pointer',
            transition: 'all 0.3s ease',
            marginBottom: '16px'
          }}
          onDragOver={handleDragOver}
          onDragLeave={handleDragLeave}
          onDrop={handleDrop}
          onClick={() => {
            const input = document.createElement('input')
            input.type = 'file'
            input.multiple = true
            input.accept = 'image/*'
            input.onchange = (e) => handleFileSelect(e.target.files)
            input.click()
          }}
        >
          <Upload size={32} color={dragOver ? '#007bff' : '#666'} style={{ marginBottom: '8px' }} />
          <div style={{ color: '#666', fontSize: '14px' }}>
            {uploading ? '上传中...' : '点击或拖拽图片到此处上传'}
          </div>
          <div style={{ color: '#999', fontSize: '12px', marginTop: '4px' }}>
            支持 JPG、PNG、GIF 格式，单个文件不超过 10MB
          </div>
        </div>
      )}

      {/* 图片列表 */}
      {(images.length > 0 || tempFiles.length > 0) && (
        <div style={{ marginTop: '16px' }}>
          {!readOnly && (
            <div style={{ fontSize: '14px', fontWeight: 'bold', marginBottom: '8px', color: '#333' }}>
              图片 ({images.length + tempFiles.length})
            </div>
          )}
          <div style={{
            display: 'grid',
            gridTemplateColumns: readOnly ? 'repeat(auto-fill, minmax(200px, 1fr))' : 'repeat(auto-fill, minmax(120px, 1fr))',
            gap: '12px'
          }}>
            {/* 显示已上传的图片 */}
            {images.map((image) => (
              <div key={image.id} style={{
                border: '1px solid #ddd',
                borderRadius: '8px',
                padding: '8px',
                backgroundColor: 'white',
                position: 'relative'
              }}>
                {/* 图片预览 */}
                <div style={{
                  width: '100%',
                  height: readOnly ? '150px' : '80px',
                  backgroundColor: '#f5f5f5',
                  borderRadius: '4px',
                  display: 'flex',
                  alignItems: 'center',
                  justifyContent: 'center',
                  marginBottom: '8px',
                  overflow: 'hidden'
                }}>
                  <img
                    src={equipmentMaintenanceAPI.repairRecordImages.preview(image.id)}
                    alt={image.original_filename}
                    style={{
                      maxWidth: '100%',
                      maxHeight: '100%',
                      objectFit: 'cover'
                    }}
                    onError={(e) => {
                      e.target.style.display = 'none'
                      e.target.nextSibling.style.display = 'flex'
                    }}
                  />
                  <div style={{
                    display: 'none',
                    alignItems: 'center',
                    justifyContent: 'center',
                    color: '#999',
                    fontSize: '12px'
                  }}>
                    图片加载失败
                  </div>
                </div>

                {/* 文件信息 */}
                <div style={{ fontSize: '12px', color: '#666', marginBottom: '8px' }}>
                  <div style={{ 
                    overflow: 'hidden', 
                    textOverflow: 'ellipsis', 
                    whiteSpace: 'nowrap',
                    marginBottom: '2px'
                  }}>
                    {image.original_filename}
                  </div>
                  <div>{image.file_size_human_readable}</div>
                </div>

                {/* 操作按钮 */}
                <div style={{
                  display: 'flex',
                  justifyContent: 'space-between',
                  gap: '4px'
                }}>
                  <button
                    onClick={(e) => {
                      e.stopPropagation()
                      handlePreview(image.id)
                    }}
                    style={{
                      padding: '4px 6px',
                      backgroundColor: '#007bff',
                      color: 'white',
                      border: 'none',
                      borderRadius: '3px',
                      cursor: 'pointer',
                      fontSize: '11px',
                      display: 'flex',
                      alignItems: 'center',
                      gap: '2px'
                    }}
                    title="预览"
                  >
                    <Eye size={12} />
                    预览
                  </button>
                  <button
                    onClick={(e) => {
                      e.stopPropagation()
                      handleDownload(image.id)
                    }}
                    style={{
                      padding: '4px 6px',
                      backgroundColor: '#28a745',
                      color: 'white',
                      border: 'none',
                      borderRadius: '3px',
                      cursor: 'pointer',
                      fontSize: '11px',
                      display: 'flex',
                      alignItems: 'center',
                      gap: '2px'
                    }}
                    title="下载"
                  >
                    <Download size={12} />
                    下载
                  </button>
                  {!readOnly && (
                    <button
                      onClick={(e) => {
                        e.stopPropagation()
                        handleDelete(image.id)
                      }}
                      style={{
                        padding: '4px 6px',
                        backgroundColor: '#dc3545',
                        color: 'white',
                        border: 'none',
                        borderRadius: '3px',
                        cursor: 'pointer',
                        fontSize: '11px',
                        display: 'flex',
                        alignItems: 'center',
                        gap: '2px'
                      }}
                      title="删除"
                    >
                      <Trash2 size={12} />
                      删除
                    </button>
                  )}
                </div>
              </div>
            ))}
            
            {/* 显示临时文件 */}
            {tempFiles.map((tempFile) => (
              <div key={tempFile.id} style={{
                border: '1px solid #ddd',
                borderRadius: '8px',
                padding: '8px',
                backgroundColor: '#fff8dc', // 浅黄色背景表示临时文件
                position: 'relative'
              }}>
                {/* 临时标识 */}
                <div style={{
                  position: 'absolute',
                  top: '4px',
                  right: '4px',
                  backgroundColor: '#ffc107',
                  color: 'white',
                  fontSize: '10px',
                  padding: '2px 4px',
                  borderRadius: '2px'
                }}>
                  待上传
                </div>
                
                {/* 图片预览 */}
                <div style={{
                  width: '100%',
                  height: readOnly ? '150px' : '80px',
                  backgroundColor: '#f5f5f5',
                  borderRadius: '4px',
                  display: 'flex',
                  alignItems: 'center',
                  justifyContent: 'center',
                  marginBottom: '8px',
                  overflow: 'hidden'
                }}>
                  <img
                    src={tempFile.preview}
                    alt={tempFile.name}
                    style={{
                      maxWidth: '100%',
                      maxHeight: '100%',
                      objectFit: 'cover'
                    }}
                  />
                </div>

                {/* 文件信息 */}
                <div style={{ fontSize: '12px', color: '#666', marginBottom: '8px' }}>
                  <div style={{ 
                    overflow: 'hidden', 
                    textOverflow: 'ellipsis', 
                    whiteSpace: 'nowrap',
                    marginBottom: '2px'
                  }}>
                    {tempFile.name}
                  </div>
                  <div>{(tempFile.size / 1024 / 1024).toFixed(2)} MB</div>
                </div>

                {/* 操作按钮 */}
                <div style={{
                  display: 'flex',
                  justifyContent: 'flex-end',
                  gap: '4px'
                }}>
                  <button
                    onClick={(e) => {
                      e.stopPropagation()
                      handleDelete(tempFile.id)
                    }}
                    style={{
                      padding: '4px 6px',
                      backgroundColor: '#dc3545',
                      color: 'white',
                      border: 'none',
                      borderRadius: '3px',
                      cursor: 'pointer',
                      fontSize: '11px',
                      display: 'flex',
                      alignItems: 'center',
                      gap: '2px'
                    }}
                  >
                    <Trash2 size={12} />
                    删除
                  </button>
                </div>
              </div>
            ))}
          </div>
        </div>
      )}
    </div>
  )
})

export default ImageUpload